﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Com.ContentRendering.Api.LoaderEngine
{
    /// <summary/>
    internal class StringSplit
    {
        /// <summary/>
        internal static List<string> Split(
            string input,
            string[] separators)
        {
            List<string> sections = new List<string>();

            // add to the sections
            sections.Add(input);

            foreach (string separator in separators)
            {
                int index = 0;

                while (index < sections.Count)
                {
                    // split the section into new sections
                    List<string> newSections = StringSplit.Split(sections[index], separator);

                    // move on if nothing was split
                    if (newSections.Count== 1)
                    {
                        // increase the counter
                        index++;
                    }
                    else
                    {
                        // replace the range
                        sections.RemoveAt(index);
                        sections.InsertRange(index, newSections);

                        // increase the index
                        index += newSections.Count;
                    }
                }
            }

            // return the range
            return sections;
        }

        /// <summary/>
        private static List<string> Split(
            string input,
            string separator)
        {
            List<string> sections = new List<string>();

            int previousIndex = 0;

            while (true)
            {
                // find the occurance
                int index = input.IndexOf(separator, previousIndex);

                // exit if not found
                if (index == Constant.NOT_FOUND)
                {
                    break;
                }

                // add the previous section
                if (previousIndex != index)
                {
                    sections.Add(input.Substring(previousIndex, index - previousIndex));
                }

                // add the separator section
                sections.Add(input.Substring(index, separator.Length));

                // move on
                previousIndex = index + separator.Length;
            }

            // add the tail section
            if (previousIndex != input.Length)
            {
                sections.Add(input.Substring(previousIndex, input.Length - previousIndex));
            }

            // return as an array
            return sections;
        }
    }
}
